package com.karaoke.android.library.mvvm

import android.content.Context
import android.databinding.BaseObservable
import android.os.Bundle
import android.view.View
import com.trello.rxlifecycle.LifecycleProvider
import com.trello.rxlifecycle.LifecycleTransformer
import com.trello.rxlifecycle.RxLifecycle
import com.trello.rxlifecycle.android.FragmentEvent
import com.trello.rxlifecycle.android.RxLifecycleAndroid
import com.karaoke.android.library.mvvm.MvvmViewModel
import rx.Observable
import rx.subjects.BehaviorSubject

/**
 * Created by Administrator on 2016/12/2.
 */
abstract class FragmentViewModel : MvvmViewModel, LifecycleProvider<FragmentEvent>, BaseObservable()
{
    private val lifecycleSubject = BehaviorSubject.create<FragmentEvent>()
    protected var firstLaunch = true

    protected open fun onInitLoad()
    {

    }


    override fun lifecycle(): Observable<FragmentEvent>
    {
        return lifecycleSubject.asObservable()
    }

    override fun <T> bindUntilEvent(event: FragmentEvent): LifecycleTransformer<T>
    {
        return RxLifecycle.bindUntilEvent<T, FragmentEvent>(lifecycleSubject, event)
    }

    override fun <T> bindToLifecycle(): LifecycleTransformer<T>
    {
        return RxLifecycleAndroid.bindFragment<T>(lifecycleSubject)
    }

    fun onAttach(context: Context?)
    {
        lifecycleSubject.onNext(FragmentEvent.ATTACH)
    }

    fun onCreate(savedInstanceState: Bundle?)
    {
        lifecycleSubject.onNext(FragmentEvent.CREATE)
        onCreate()
    }

    override fun onCreate()
    {

    }

    open fun onViewCreated(view: View?, savedInstanceState: Bundle?)
    {
        lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW)
        if (firstLaunch)
            onInitLoad()
    }

    override fun onStart()
    {
        lifecycleSubject.onNext(FragmentEvent.START)
    }

    override fun onResume()
    {
        lifecycleSubject.onNext(FragmentEvent.RESUME)
    }

    override fun onPause()
    {
        lifecycleSubject.onNext(FragmentEvent.PAUSE)
    }

    override fun onStop()
    {
        lifecycleSubject.onNext(FragmentEvent.STOP)
    }

    open fun onDestroyView()
    {
        lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW)
        firstLaunch = false
    }

    override fun onDestroy()
    {
        lifecycleSubject.onNext(FragmentEvent.DESTROY)
        firstLaunch = false
    }

    fun onDetach()
    {
        lifecycleSubject.onNext(FragmentEvent.DETACH)
    }
}